//留言板页面组件
import EditorComment from "./components/editor"
import ListComment from "./components/list"
import { Pagination } from "antd"
import { useEffect, useState } from "react"

const BaseComment = ({ request = () => { }, pageInfo = null }) => {
    const [commentList, setCommentList] = useState([]); // 评论数据

    const [loading, setLoading] = useState(false);
    const [total, setTotal] = useState(0);

    const [pageConfig, setPageConfig] = useState({  // 分页数据
        page: pageInfo?.page || 1,
        pageSize: pageInfo?.pageSize || 10
    })

    useEffect(() => {
        setLoading(true);
        const res = request({ pageConfig }); // 调用request
        if (!(res instanceof Promise)) {
            throw new Error(`request 返回值必须是promise实例`)
        }
        res.then(val => {
            setLoading(false);
            setCommentList(val.data); // 设置评论数据
            setTotal(val.total);//评论总数
        })
    }, [request, pageConfig])


    const handleChange = (page, pageSize) => {

        setPageConfig({ //设置页面的当前页面和总页数
            page,
            pageSize
        })
    }
    const handleShowEditor = (item) => {
        item.isShowEditor = !item.isShowEditor;
        setCommentList((val) => [...val]);
    }
    return (
        <>
            <h2>评论</h2>
            <EditorComment
                placeholder={'请输入评论内容（支持 Markdown）'}
                onClickShowEditor={handleShowEditor}
            />
            <ListComment
                lists={commentList}
                onClickShowEditor={handleShowEditor}
            />

            {
                pageInfo && (
                    <Pagination
                        style={{ marginLeft: '35%' }}
                        {...pageInfo}
                        disabled={loading}
                        current={pageConfig.page}//当前页码
                        total={total}
                        pageSize={pageConfig.pageSize} //总页码
                        onChange={handleChange}
                    />
                )
            }

        </>
    )
}

export default BaseComment;

export { EditorComment, ListComment };